package JavaConcurrentMei.一;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

public class ProducerAndConsumer {
    private static int max_size = 3;
    private static ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(max_size);

    public static void main(String[] args) throws Exception{
        // 生产线程
        new Thread(() -> {
            synchronized (queue) {
                for(int i=0; i<5; i++) {
                    // 队列满，则等待
                    while (queue.size() == max_size) {
                        try {
                            // 挂起线程，释放锁，等待消费线程消费
                            queue.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    // 生产资源
                    queue.add(new Random().nextInt());
                    System.out.println(Thread.currentThread().getName()+"生产资源：" + queue.peek());
                    queue.notifyAll();
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1").start();

        // 消费线程
        new Thread(() -> {
            synchronized (queue) {
                for(int i=0; i<5; i++) {
                    // 队列空，等待
                    while (queue.isEmpty()) {
                        try {
                            queue.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    // 消费资源
                    try {
                        System.out.println(Thread.currentThread().getName()+"消费资源：" + queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    queue.notifyAll();
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t2").start();
    }
}
